/**
 * 筛选面板组件
 * 提供统一的筛选条件界面，支持多种筛选器类型
 */
class FilterPanel extends BaseComponent {
    constructor(options = {}) {
        super({
            ...options,
            className: `filter-panel ${options.className || ''}`
        });

        // 组件配置
        this.title = options.title || '筛选条件';
        this.filters = options.filters || [];
        this.onApply = options.onApply || null;
        this.onReset = options.onReset || null;
        this.collapsible = options.collapsible !== false;
        this.collapsed = options.collapsed || false;
        this.showActions = options.showActions !== false;
        this.layout = options.layout || 'grid'; // 'grid' or 'vertical'

        // 筛选器值
        this.values = {};

        // 初始化筛选器
        this.initializeFilters();
    }

    /**
     * 初始化筛选器配置
     */
    initializeFilters() {
        // 为每个筛选器生成唯一ID
        this.filters = this.filters.map((filter, index) => ({
            ...filter,
            id: filter.id || `filter_${index}`,
            value: filter.value || '',
            options: filter.options || [],
            required: filter.required || false
        }));
    }

    /**
     * 渲染筛选面板
     */
    render() {
        const template = `
            <div class="filter-panel-wrapper ${this.className}" data-component-id="${this.id}">
                <div class="bg-white rounded-lg border border-slate-200 shadow-sm">
                    ${this.renderHeader()}
                    ${this.collapsed ? '' : this.renderBody()}
                </div>
            </div>
        `;

        // 创建或更新元素
        if (!this.element) {
            this.element = this.createElementFromTemplate(template);
        } else {
            this.element.outerHTML = template;
            this.element = this.container.querySelector(`[data-component-id="${this.id}"]`);
        }

        // 初始化筛选器
        this.initializeFilterElements();

        // 绑定事件
        this.bindEvents();
    }

    /**
     * 渲染面板头部
     */
    renderHeader() {
        const collapseIcon = this.collapsed ? 'fa-chevron-down' : 'fa-chevron-up';

        return `
            <div class="px-6 py-4 border-b border-slate-200">
                <div class="flex items-center justify-between">
                    <div class="flex items-center space-x-3">
                        <h3 class="text-lg font-semibold text-slate-800">${this.title}</h3>
                        <span class="inline-flex items-center px-2.5 py-0.5 rounded-full text-xs font-medium bg-slate-100 text-slate-800">
                            ${this.getActiveFilterCount()} 个条件
                        </span>
                    </div>
                    <div class="flex items-center space-x-2">
                        ${this.collapsible ? `
                            <button class="collapse-btn p-2 text-slate-500 hover:text-slate-700 hover:bg-slate-100 rounded-lg transition-colors" title="${this.collapsed ? '展开' : '收起'}">
                                <i class="fas ${collapseIcon}"></i>
                            </button>
                        ` : ''}
                        ${this.showActions ? `
                            <button class="reset-btn px-3 py-1.5 text-sm border border-slate-300 text-slate-700 rounded-lg hover:bg-slate-50 transition-colors">
                                <i class="fas fa-redo mr-1"></i>重置
                            </button>
                            <button class="apply-btn px-4 py-1.5 text-sm bg-blue-600 text-white rounded-lg hover:bg-blue-700 transition-colors">
                                <i class="fas fa-filter mr-1"></i>应用筛选
                            </button>
                        ` : ''}
                    </div>
                </div>
            </div>
        `;
    }

    /**
     * 渲染面板主体
     */
    renderBody() {
        const gridClass = this.layout === 'grid' ? 'grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 xl:grid-cols-4 gap-4' : 'space-y-4';

        return `
            <div class="p-6">
                <div class="${gridClass}">
                    ${this.filters.map(filter => this.renderFilter(filter)).join('')}
                </div>
            </div>
        `;
    }

    /**
     * 渲染单个筛选器
     */
    renderFilter(filter) {
        const { id, type, label, placeholder, required, options, value } = filter;

        const requiredMark = required ? '<span class="text-red-500 ml-1">*</span>' : '';

        switch (type) {
            case 'text':
                return `
                    <div class="filter-item" data-filter-id="${id}">
                        <label class="block text-sm font-medium text-slate-700 mb-2">
                            ${label}${requiredMark}
                        </label>
                        <input type="text"
                               class="filter-input w-full px-3 py-2 border border-slate-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-transparent"
                               placeholder="${placeholder || `请输入${label}`}"
                               value="${value || ''}"
                               data-filter-id="${id}">
                    </div>
                `;

            case 'select':
                return `
                    <div class="filter-item" data-filter-id="${id}">
                        <label class="block text-sm font-medium text-slate-700 mb-2">
                            ${label}${requiredMark}
                        </label>
                        <select class="filter-select w-full px-3 py-2 border border-slate-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-transparent"
                                data-filter-id="${id}">
                            <option value="">请选择${label}</option>
                            ${options.map(option => `
                                <option value="${option.value}" ${value === option.value ? 'selected' : ''}>
                                    ${option.label}
                                </option>
                            `).join('')}
                        </select>
                    </div>
                `;

            case 'date':
                return `
                    <div class="filter-item" data-filter-id="${id}">
                        <label class="block text-sm font-medium text-slate-700 mb-2">
                            ${label}${requiredMark}
                        </label>
                        <input type="date"
                               class="filter-input w-full px-3 py-2 border border-slate-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-transparent"
                               value="${value || ''}"
                               data-filter-id="${id}">
                    </div>
                `;

            case 'daterange':
                return `
                    <div class="filter-item" data-filter-id="${id}">
                        <label class="block text-sm font-medium text-slate-700 mb-2">
                            ${label}${requiredMark}
                        </label>
                        <div class="flex space-x-2">
                            <input type="date"
                                   class="filter-input-start w-full px-3 py-2 border border-slate-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-transparent"
                                   placeholder="开始日期"
                                   value="${value?.start || ''}"
                                   data-filter-id="${id}">
                            <input type="date"
                                   class="filter-input-end w-full px-3 py-2 border border-slate-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-transparent"
                                   placeholder="结束日期"
                                   value="${value?.end || ''}"
                                   data-filter-id="${id}">
                        </div>
                    </div>
                `;

            case 'number':
                return `
                    <div class="filter-item" data-filter-id="${id}">
                        <label class="block text-sm font-medium text-slate-700 mb-2">
                            ${label}${requiredMark}
                        </label>
                        <input type="number"
                               class="filter-input w-full px-3 py-2 border border-slate-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-transparent"
                               placeholder="${placeholder || `请输入${label}`}"
                               value="${value || ''}"
                               min="${filter.min || ''}"
                               max="${filter.max || ''}"
                               step="${filter.step || '1'}"
                               data-filter-id="${id}">
                    </div>
                `;

            case 'checkbox':
                return `
                    <div class="filter-item" data-filter-id="${id}">
                        <label class="flex items-center space-x-2 cursor-pointer">
                            <input type="checkbox"
                                   class="filter-checkbox w-4 h-4 text-blue-600 border-slate-300 rounded focus:ring-blue-500"
                                   ${value ? 'checked' : ''}
                                   data-filter-id="${id}">
                            <span class="text-sm font-medium text-slate-700">${label}</span>
                            ${requiredMark}
                        </label>
                    </div>
                `;

            case 'multiselect':
                return `
                    <div class="filter-item" data-filter-id="${id}">
                        <label class="block text-sm font-medium text-slate-700 mb-2">
                            ${label}${requiredMark}
                        </label>
                        <div class="multiselect-container">
                            ${options.map(option => `
                                <label class="flex items-center space-x-2 mb-2 cursor-pointer">
                                    <input type="checkbox"
                                           class="filter-multiselect w-4 h-4 text-blue-600 border-slate-300 rounded focus:ring-blue-500"
                                           value="${option.value}"
                                           ${(value || []).includes(option.value) ? 'checked' : ''}
                                           data-filter-id="${id}">
                                    <span class="text-sm text-slate-700">${option.label}</span>
                                </label>
                            `).join('')}
                        </div>
                    </div>
                `;

            default:
                return '';
        }
    }

    /**
     * 从模板创建元素
     */
    createElementFromTemplate(template) {
        const div = document.createElement('div');
        div.innerHTML = template.trim();
        return div.firstElementChild;
    }

    /**
     * 初始化筛选器元素
     */
    initializeFilterElements() {
        if (!this.element) return;

        // 恢复筛选器值
        this.filters.forEach(filter => {
            const filterElement = this.element.querySelector(`[data-filter-id="${filter.id}"]`);
            if (filterElement) {
                const input = filterElement.querySelector('input, select');
                if (input) {
                    if (filter.type === 'checkbox') {
                        input.checked = filter.value || false;
                    } else if (filter.type === 'multiselect') {
                        const checkboxes = filterElement.querySelectorAll('input[type="checkbox"]');
                        checkboxes.forEach(checkbox => {
                            checkbox.checked = (filter.value || []).includes(checkbox.value);
                        });
                    } else {
                        input.value = filter.value || '';
                    }
                }
            }
        });
    }

    /**
     * 绑定事件
     */
    bindEvents() {
        if (!this.element) return;

        // 折叠/展开
        const collapseBtn = this.element.querySelector('.collapse-btn');
        if (collapseBtn) {
            collapseBtn.addEventListener('click', () => {
                this.toggleCollapse();
            });
        }

        // 重置按钮
        const resetBtn = this.element.querySelector('.reset-btn');
        if (resetBtn) {
            resetBtn.addEventListener('click', () => {
                this.reset();
            });
        }

        // 应用筛选按钮
        const applyBtn = this.element.querySelector('.apply-btn');
        if (applyBtn) {
            applyBtn.addEventListener('click', () => {
                this.applyFilters();
            });
        }

        // 输入框变化事件
        const inputs = this.element.querySelectorAll('input, select');
        inputs.forEach(input => {
            input.addEventListener('change', (e) => {
                this.handleInputChange(e);
            });

            // 实时输入事件
            if (input.type === 'text') {
                input.addEventListener('input', (e) => {
                    this.handleInputChange(e);
                });
            }
        });
    }

    /**
     * 处理输入变化
     */
    handleInputChange(event) {
        const filterId = event.target.dataset.filterId;
        const filter = this.filters.find(f => f.id === filterId);

        if (!filter) return;

        const filterElement = event.target.closest('.filter-item');

        switch (filter.type) {
            case 'text':
            case 'select':
            case 'date':
            case 'number':
                filter.value = event.target.value;
                break;

            case 'daterange':
                const isStart = event.target.classList.contains('filter-input-start');
                if (!filter.value) filter.value = {};
                filter.value[isStart ? 'start' : 'end'] = event.target.value;
                break;

            case 'checkbox':
                filter.value = event.target.checked;
                break;

            case 'multiselect':
                const checkboxes = filterElement.querySelectorAll('input[type="checkbox"]:checked');
                filter.value = Array.from(checkboxes).map(cb => cb.value);
                break;
        }

        // 更新计数器
        this.updateActiveFilterCount();

        // 触发变化事件
        this.emit('filterChanged', { filterId, value: filter.value });
    }

    /**
     * 切换折叠状态
     */
    toggleCollapse() {
        this.collapsed = !this.collapsed;
        this.render();
        this.emit(this.collapsed ? 'collapsed' : 'expanded');
    }

    /**
     * 应用筛选条件
     */
    applyFilters() {
        const values = this.getFilterValues();

        // 验证必填项
        const validation = this.validateFilters();
        if (!validation.valid) {
            this.showValidationError(validation.errors);
            return;
        }

        // 更新值
        this.values = values;

        // 触发应用事件
        this.emit('apply', { values });

        if (this.onApply) {
            this.onApply.call(this, values);
        }
    }

    /**
     * 重置筛选条件
     */
    reset() {
        // 重置所有筛选器值
        this.filters.forEach(filter => {
            switch (filter.type) {
                case 'text':
                case 'select':
                case 'date':
                case 'number':
                    filter.value = '';
                    break;
                case 'daterange':
                    filter.value = { start: '', end: '' };
                    break;
                case 'checkbox':
                    filter.value = false;
                    break;
                case 'multiselect':
                    filter.value = [];
                    break;
            }
        });

        // 重新渲染
        this.render();

        // 清空值
        this.values = {};

        // 触发重置事件
        this.emit('reset');

        if (this.onReset) {
            this.onReset.call(this);
        }
    }

    /**
     * 获取筛选器值
     */
    getFilterValues() {
        const values = {};
        this.filters.forEach(filter => {
            values[filter.id] = filter.value;
        });
        return values;
    }

    /**
     * 验证筛选器
     */
    validateFilters() {
        const errors = [];

        this.filters.forEach(filter => {
            if (filter.required) {
                const hasValue = filter.type === 'multiselect'
                    ? (filter.value || []).length > 0
                    : filter.value !== '' && filter.value !== null && filter.value !== undefined;

                if (!hasValue) {
                    errors.push({
                        filterId: filter.id,
                        message: `${filter.label}为必填项`
                    });
                }
            }
        });

        return {
            valid: errors.length === 0,
            errors
        };
    }

    /**
     * 显示验证错误
     */
    showValidationError(errors) {
        errors.forEach(error => {
            const filterElement = this.element.querySelector(`[data-filter-id="${error.filterId}"]`);
            if (filterElement) {
                filterElement.classList.add('border-red-200');
                const input = filterElement.querySelector('input, select');
                if (input) {
                    input.classList.add('border-red-500');
                }

                // 显示错误信息
                let errorElement = filterElement.querySelector('.filter-error');
                if (!errorElement) {
                    errorElement = document.createElement('div');
                    errorElement.className = 'filter-error text-red-500 text-sm mt-1';
                    filterElement.appendChild(errorElement);
                }
                errorElement.textContent = error.message;
            }
        });

        // 3秒后清除错误状态
        setTimeout(() => {
            this.clearValidationErrors();
        }, 3000);
    }

    /**
     * 清除验证错误
     */
    clearValidationErrors() {
        const errorElements = this.element.querySelectorAll('.filter-error');
        errorElements.forEach(el => el.remove());

        const filterElements = this.element.querySelectorAll('.filter-item');
        filterElements.forEach(el => {
            el.classList.remove('border-red-200');
            const input = el.querySelector('input, select');
            if (input) {
                input.classList.remove('border-red-500');
            }
        });
    }

    /**
     * 获取激活的筛选器数量
     */
    getActiveFilterCount() {
        return this.filters.filter(filter => {
            if (filter.type === 'multiselect') {
                return (filter.value || []).length > 0;
            } else if (filter.type === 'daterange') {
                return filter.value?.start || filter.value?.end;
            } else if (filter.type === 'checkbox') {
                return filter.value === true;
            } else {
                return filter.value !== '' && filter.value !== null && filter.value !== undefined;
            }
        }).length;
    }

    /**
     * 更新激活筛选器计数
     */
    updateActiveFilterCount() {
        const countElement = this.element.querySelector('.rounded-full');
        if (countElement) {
            countElement.textContent = `${this.getActiveFilterCount()} 个条件`;
        }
    }

    /**
     * 设置筛选器值
     */
    setFilterValue(filterId, value) {
        const filter = this.filters.find(f => f.id === filterId);
        if (filter) {
            filter.value = value;
            this.render();
        }
        return this;
    }

    /**
     * 批量设置筛选器值
     */
    setFilterValues(values) {
        Object.keys(values).forEach(filterId => {
            this.setFilterValue(filterId, values[filterId]);
        });
        return this;
    }

    /**
     * 获取筛选器配置
     */
    getFilters() {
        return this.filters;
    }

    /**
     * 添加筛选器
     */
    addFilter(filter) {
        this.filters.push(filter);
        this.render();
        return this;
    }

    /**
     * 移除筛选器
     */
    removeFilter(filterId) {
        this.filters = this.filters.filter(f => f.id !== filterId);
        this.render();
        return this;
    }

    /**
     * 设置加载状态
     */
    setLoading(loading) {
        const applyBtn = this.element.querySelector('.apply-btn');
        if (applyBtn) {
            if (loading) {
                applyBtn.disabled = true;
                applyBtn.innerHTML = '<i class="fas fa-spinner fa-spin mr-1"></i>应用中...';
            } else {
                applyBtn.disabled = false;
                applyBtn.innerHTML = '<i class="fas fa-filter mr-1"></i>应用筛选';
            }
        }
        return this;
    }
}

// 导出组件
window.FilterPanel = FilterPanel;